package com.xixibaby.mybatis.config;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author tomj
 */
@Configuration
@ConfigurationProperties(prefix = "spring.datasource.dynamic")
public class TransactionalManagerConfig {

    @Resource
    private DynamicRoutingDataSource dynamicRoutingDataSource;

    @Bean(name = "transactionManagers")
    public Map<String, DataSourceTransactionManager> transactionManagers(){
        Map<String, DataSource> currentDataSources = dynamicRoutingDataSource.getCurrentDataSources();
        Map<String, DataSourceTransactionManager> managerMap = new HashMap<>(8);
        currentDataSources.keySet().forEach(key -> {
            DataSourceTransactionManager manager = new DataSourceTransactionManager();
            DefaultTransactionDefinition def = new DefaultTransactionDefinition();
            def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
            manager.setDataSource(currentDataSources.get(key));
            managerMap.put(key,manager);
        });
        return managerMap;
    }


}
